
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MD5Util {
	
	private static Log log = LogFactory.getLog(MD5Util.class);
	/**
	 * 对一个文件获取md5值
	 * 
	 * @return md5串
	 */
	public static String getMD5(File file)
	{
		FileInputStream fileInputStream = null;
		try 
		{
			fileInputStream = new FileInputStream(file);
			byte[] buffer = new byte[2048];
			int length = 0;
			MessageDigest MD5 = MessageDigest.getInstance("MD5");
			while ((length = fileInputStream.read(buffer)) != -1) 
			{
				MD5.update(buffer, 0, length);
			}
			return new String(Hex.encodeHex(MD5.digest()));
		}
		catch (Exception e) 
		{
			log.error("获取文件MD5码失败",e);
			return null;
		}  
		finally 
		{
			try 
			{
				if(fileInputStream != null)
				{
					fileInputStream.close();
				}
			}
			catch (IOException e)
			{
				log.error("关闭文件流失败",e);
			}
		}
	}
	public static void main(String[] args) {
		File f = new File("d:\\root\\bak\\20171015_jl_e81d2d675972e848c323c1b4cb778096.xlsx");
		String s = getMD5(f);
		System.out.println("s:"+s);
	}
}